package com.zrf.gulimall.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrf.gulimall.commnon.core.enums.ProductStatusEnum;
import com.zrf.gulimall.commnon.core.es.SkuEsModel;
import com.zrf.gulimall.commnon.core.to.SkuHasStockVo;
import com.zrf.gulimall.commnon.core.to.SkuReductionTo;
import com.zrf.gulimall.commnon.core.to.SpuBoundTo;
import com.zrf.gulimall.common.database.utils.PageUtils;
import com.zrf.gulimall.common.database.utils.Query;
import com.zrf.gulimall.commnon.core.utils.R;
import com.zrf.gulimall.product.dao.SpuInfoDao;
import com.zrf.gulimall.product.entity.*;
import com.zrf.gulimall.product.feign.CouponFeignService;
import com.zrf.gulimall.product.feign.SearchFeignService;
import com.zrf.gulimall.product.feign.WareFeignService;
import com.zrf.gulimall.product.service.*;
import com.zrf.gulimall.product.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;


@Service("spuInfoService")
@Slf4j
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

	@Autowired
	SpuInfoDescService spuInfoDescService;

	@Autowired
	SpuImagesService spuImagesService;

	@Autowired
	AttrService attrService;

	@Autowired
	ProductAttrValueService attrValueService;

	@Autowired
	SkuInfoService skuInfoService;
	@Autowired
	SkuImagesService skuImagesService;

	@Autowired
	SkuSaleAttrValueService skuSaleAttrValueService;

	@Autowired
	private CouponFeignService couponFeignService;

	@Autowired
	private BrandService brandService;

	@Autowired
	private CategoryService categoryService;

	@Autowired
	private WareFeignService wareFeignService;

	@Autowired
	private SearchFeignService searchFeignService;

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		String key = (String) params.get("key");
		String status = (String) params.get("status");
		String brandId = (String) params.get("brandId");
		String catelogId = (String) params.get("catelogId");
		IPage<SpuInfoEntity> page = this.lambdaQuery()
				.eq(StrUtil.isNotEmpty(status), SpuInfoEntity::getPublishStatus, status)
				.eq(StrUtil.isNotEmpty(brandId) && !"0".equals(brandId), SpuInfoEntity::getBrandId, brandId)
				.eq(StrUtil.isNotEmpty(catelogId) && !"0".equals(catelogId), SpuInfoEntity::getCatalogId, catelogId)
				.and(StrUtil.isNotEmpty(key), wrapper -> wrapper.eq(SpuInfoEntity::getId, key).or().like(SpuInfoEntity::getSpuName, key))
				.page(new Query<SpuInfoEntity>().getPage(params));
		return new PageUtils(page);
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public void saveSpuInfo(SpuSaveVo spuSaveVo) {
		//1、保存spu基本信息 pms_spu_info
		SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
		BeanUtils.copyProperties(spuSaveVo, spuInfoEntity);
		spuInfoEntity.setCreateTime(new Date());
		spuInfoEntity.setUpdateTime(new Date());
		this.save(spuInfoEntity);

		//2、保存Spu的描述图片 pms_spu_info_desc
		List<String> decript = spuSaveVo.getDecript();
		SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
		descEntity.setSpuId(spuInfoEntity.getId());
		descEntity.setDecript(String.join(",", decript));
		spuInfoDescService.save(descEntity);

		//3、保存spu的图片集 pms_spu_images
		List<String> images = spuSaveVo.getImages();
		if (CollUtil.isNotEmpty(images)) {
			List<SpuImagesEntity> spuImagesEntities = images.stream().map(item -> {
				SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
				spuImagesEntity.setSpuId(spuInfoEntity.getId());
				spuImagesEntity.setImgUrl(item);
				return spuImagesEntity;
			}).collect(Collectors.toList());
			spuImagesService.saveBatch(spuImagesEntities);
		}

		//4、保存spu的规格参数;pms_product_attr_value
		List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
		List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(attr -> {
			ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
			valueEntity.setAttrId(attr.getAttrId());
			AttrEntity id = attrService.getById(attr.getAttrId());
			valueEntity.setAttrName(id.getAttrName());
			valueEntity.setAttrValue(attr.getAttrValues());
			valueEntity.setQuickShow(attr.getShowDesc());
			valueEntity.setSpuId(spuInfoEntity.getId());
			return valueEntity;
		}).collect(Collectors.toList());
		attrValueService.saveBatch(productAttrValueEntities);

		//5、保存spu的积分信息；gulimall_sms->sms_spu_bounds
		Bounds bounds = spuSaveVo.getBounds();
		SpuBoundTo spuBoundTo = new SpuBoundTo();
		BeanUtils.copyProperties(bounds, spuBoundTo);
		spuBoundTo.setSpuId(spuInfoEntity.getId());
		R r = couponFeignService.saveSpuBounds(spuBoundTo);
		if (r.getCode() != 0) {
			log.error("远程保存spu积分信息失败");
		}

		//5、保存当前spu对应的所有sku信息；
		List<Skus> skus = spuSaveVo.getSkus();
		if (CollUtil.isNotEmpty(skus)) {
			skus.forEach(item -> {
				String defaultImg = "";
				for (Images image : item.getImages()) {
					if (image.getDefaultImg() == 1) {
						defaultImg = image.getImgUrl();
					}
				}
				SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
				BeanUtils.copyProperties(item, skuInfoEntity);
				skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
				skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
				skuInfoEntity.setSaleCount(0L);
				skuInfoEntity.setSpuId(spuInfoEntity.getId());
				skuInfoEntity.setSkuDefaultImg(defaultImg);
				//5.1）、sku的基本信息；pms_sku_info
				skuInfoService.save(skuInfoEntity);

				Long skuId = skuInfoEntity.getSkuId();

				List<SkuImagesEntity> imagesEntities = item.getImages().stream().map(img -> {
					SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
					skuImagesEntity.setSkuId(skuId);
					skuImagesEntity.setImgUrl(img.getImgUrl());
					skuImagesEntity.setDefaultImg(img.getDefaultImg());
					return skuImagesEntity;
				}).filter(entity -> {
					//返回true就是需要，false就是剔除
					return StrUtil.isNotEmpty(entity.getImgUrl());
				}).collect(Collectors.toList());
				//5.2）、sku的图片信息；pms_sku_image
				skuImagesService.saveBatch(imagesEntities);

				List<Attr> attr = item.getAttr();
				List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(a -> {
					SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity();
					BeanUtils.copyProperties(a, attrValueEntity);
					attrValueEntity.setSkuId(skuId);
					return attrValueEntity;
				}).collect(Collectors.toList());
				//5.3）、sku的销售属性信息：pms_sku_sale_attr_value
				skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

				// //5.4）、sku的优惠、满减等信息；gulimall_sms->sms_sku_ladder\sms_sku_full_reduction\sms_member_price
				SkuReductionTo skuReductionTo = new SkuReductionTo();
				BeanUtils.copyProperties(item, skuReductionTo);
				skuReductionTo.setSkuId(skuId);
				if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1) {
					R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
					if (r1.getCode() != 0) {
						log.error("远程保存sku优惠信息失败");
					}
				}
			});
		}
	}

	@Override
	public void spuUp(Long spuId) {
		//1、查出当前spuId对应的所有sku信息,品牌的名字
		List<SkuInfoEntity> skuInfoEntities = skuInfoService.getSkusBySpuId(spuId);
		// 查出当前sku的所有可以被用来检索的规格属性id
		List<ProductAttrValueEntity> baseAttrs = attrValueService.queryBySpuId(spuId);
		List<Long> attrIds = baseAttrs.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
		Set<Long> attrIdSet = attrService.listByIds(attrIds).stream().filter(item -> item.getSearchType().equals(1))
				.map(AttrEntity::getAttrId).collect(Collectors.toSet());
		List<SkuEsModel.Attrs> attrsList = baseAttrs.stream().filter(item -> attrIdSet.contains(item.getAttrId()))
				.map(item -> {
					SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
					BeanUtils.copyProperties(item, attrs);
					return attrs;
				}).collect(Collectors.toList());
		// 发送远程调用，库存系统查询商品sku是否有库存
		List<Long> skuIdList = skuInfoEntities.stream()
				.map(SkuInfoEntity::getSkuId)
				.collect(Collectors.toList());
		Map<Long, Boolean> stockMap = MapUtil.newHashMap();
		try {
			R r = wareFeignService.skuHasStock(skuIdList);
			TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {
			};
			stockMap.putAll(r.getData(typeReference).stream()
					.collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock)));
		} catch (Exception e) {
			log.error("库存服务查询异常：原因{}", e.getMessage());
		}
		// 查询品牌和分类的信息
		List<Long> brandIds = skuInfoEntities.stream().map(SkuInfoEntity::getBrandId).collect(Collectors.toList());
		Map<Long, BrandEntity> brandMap = brandService.listByIds(brandIds).stream().collect(Collectors.toMap(BrandEntity::getBrandId, Function.identity()));
		List<Long> catIds = skuInfoEntities.stream().map(SkuInfoEntity::getCatalogId).collect(Collectors.toList());
		Map<Long, CategoryEntity> categoryMap = categoryService.listByIds(catIds).stream().collect(Collectors.toMap(CategoryEntity::getCatId, Function.identity()));
		//2、封装每个sku的信息
		List<SkuEsModel> collect = skuInfoEntities.stream().map(sku -> {
			//组装需要的数据
			SkuEsModel esModel = new SkuEsModel();
			BeanUtil.copyProperties(sku, esModel);
			esModel.setSkuPrice(sku.getPrice());
			esModel.setSkuImg(sku.getSkuDefaultImg());
			//设置库存信息
			esModel.setHasStock(false);
			if (Objects.nonNull(stockMap.get(sku.getSkuId())) && stockMap.get(sku.getSkuId())) {
				esModel.setHasStock(true);
			}
			// 热度评分。0
			esModel.setHotScore(0L);
			// 设置品牌和分类的名字信息
			BrandEntity brand = brandMap.get(sku.getBrandId());
			if (Objects.nonNull(brandMap.get(sku.getBrandId()))) {
				esModel.setBrandName(brand.getName());
				esModel.setBrandId(brand.getBrandId());
				esModel.setBrandImg(brand.getLogo());
			}
			CategoryEntity category = categoryMap.get(sku.getCatalogId());
			if (Objects.nonNull(category)) {
				esModel.setCatalogId(category.getCatId());
				esModel.setCatalogName(category.getName());
			}
			//设置检索属性
			esModel.setAttrs(attrsList);

			return esModel;
		}).collect(Collectors.toList());
		// 将数据发给es进行保存：service-search
		R r = searchFeignService.productStatusUp(collect);
		if (r.getCode() == 0) {
			// 远程调用成功, 修改当前spu的状态
			this.lambdaUpdate()
					.set(SpuInfoEntity::getPublishStatus, ProductStatusEnum.SPU_UP.getCode())
					.eq(SpuInfoEntity::getId, spuId)
					.update();
		} else {
			//TODO 远程调用失败，重复调用？接口幂等性:重试机制
		}
	}

	@Override
	public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
		SkuInfoEntity skuInfo = skuInfoService.getById(skuId);
		SpuInfoEntity spuInfoEntity = this.getById(skuInfo.getSpuId());
		BrandEntity brand = brandService.getById(spuInfoEntity.getBrandId());
		spuInfoEntity.setBrandName(brand.getName());
		return spuInfoEntity;
	}

}